#include <openssl/aes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rand.h>

void usage() {
    printf("\n\nusage: ./AES_encrypt [Source (plaintext)] [Passphrase] [Destination (ciphertext)] [Key File Name]\n");
}

unsigned char salt[8];
unsigned char iv[16]   = {0};
unsigned char iv2[16]  = {0};
unsigned char passphrase[] = "Any passphrase would do it!!!";
unsigned char key[16];

int    iter = 65535;
size_t len = 16;


int main(int argc, char *argv[]){  

	if(argc != 5) {
        	usage();
        	exit(1);
    	}

	unsigned char *Source;
	unsigned char *pass;
	unsigned char *Destination;	
	unsigned char *KeyF;	

	Source      = argv[1];
	pass 	    = argv[2];
	Destination = argv[3];
	KeyF	    = argv[4];

	FILE *Plaintext = fopen(Source, "r");

	fseek(Plaintext, 0L, SEEK_END);
	int PlainTextSize = ftell(Plaintext);
	fseek(Plaintext, 0L, SEEK_SET);

	unsigned char plaintext[PlainTextSize]; 
	unsigned char ciphertext[PlainTextSize + 256];
	unsigned char recoveredtext[PlainTextSize];


	AES_KEY enkey;
	AES_KEY dekey;

	printf("Passphrase is: %s\n", pass);

	PKCS5_PBKDF2_HMAC_SHA1(pass, strlen(pass), salt, sizeof(salt), iter, sizeof(key), key);

	FILE *KeyFile = fopen(KeyF, "w");

	fwrite(key, 1, sizeof(key), KeyFile);	

	AES_set_encrypt_key(key, 128, &enkey);

	RAND_bytes(salt, sizeof(salt));
	RAND_bytes(iv, 16);

	memcpy(iv2, iv, 16);
	memcpy(ciphertext, iv, 16);

	printf("generated key is: %s\n", iv);

	int read = fread(plaintext, 1, PlainTextSize, Plaintext);

	printf("plaintext detected size: %d\n", PlainTextSize);
	printf("plaintext read size: %d\n", read);
	

	AES_cbc_encrypt(plaintext,  ciphertext+sizeof(iv2),  sizeof(plaintext), &enkey, iv, AES_ENCRYPT);

	FILE *Ciphertext = fopen(Destination, "w");
	fwrite(ciphertext, 1, sizeof(ciphertext), Ciphertext);	

	fclose(Plaintext);
	fclose(Ciphertext);

	return 0;
}


